<?php

/**
 * @filename ConsumptController.php
 * @author chixiang <chixiang@dodoca.com>
 * @datetime 2016/4/21 13:53
 * @description 会员消费记录
 */
class Member_ConsumptController extends SellerController
{
    /**
     * @author chixiang <chixiang@dodoca.net>
     * @description 会员消费记录
     * @datetime 2015年5月5日
     */
    private $sellerId;
    private $userId;
    private $shopId;
    protected $role;
    protected $orderModel;
    protected $memberAttrModel;
    protected $fansModel;

    public function init()
    {
        parent::init();

        $role = $this->getCurrentUser()->getRole();
        if($role == 4)
        {
            $this->showMessage(2, '抱歉，您没有相关权限', $_SERVER['HTTP_REFERER'], '没有权限', 5);
        }
        $this->sellerId = $this->getCurrentUser()->getSellerId();
        $this->userId = $this->getCurrentUser()->get('id');
        $this->shopId = $this->getCurrentUser()->getShopId();
        $this->role = $role;
        $this->orderModel = new Order_OrderModel();
        $this->memberAttrModel = new U_CardAttrModel();
    }

    public function defaultAction()
    {
        $searchKeyword = trim($this->_request->getQuery('search_keyword', ''));
        $startDate = trim($this->_request->getQuery('start_date', ''));
        $endDate = trim($this->_request->getQuery('end_date', ''));
        $orderStatus = intval($this->_request->getQuery('order_status', ''));
        $fansLevel = trim($this->_request->getQuery('fans_level', ''));
        if ($startDate) {
            $startDate = strtotime($startDate);
        }
        if ($endDate) {
            $endDate = strtotime($endDate) + 86399;
        }
        // 分页条件
        $page = $this->_request->getQuery('page', 1);
        $page = max(intval($page), 1);
        $pageSize = intval($this->_request->getQuery('pagesize', 10));
        // 查询消费列表
        $shopId = $this->shopId;
        $consumptionList = SellerConsumptionService::consumptionList($this->sellerId, $shopId, $searchKeyword, $orderStatus, $fansLevel, $startDate, $endDate, $page, $pageSize);
        $where = array('seller_id' => $this->sellerId, 'status' => 1);
        $cardInfo = $this->memberAttrModel->select($where, array('card_name','id'));
        //获得excel基本数据
        $where = array(
            'status' => 2,
            'seller_id' => $this->sellerId,
            'shop_id' => $this->shopId
        );
        $memberImportModel = new Statistics_MemberImportModel();
        $memberImportFileModel = new Statistics_MemberImportFileModel();
        if($importFile = $memberImportFileModel->find($where,array('id','create_time'),'id DESC'))
        {
            $importFile['create_time'] = date('Y-m-d H:i', $importFile['create_time']);
            $where = array('import_file_id' => $importFile['id'], 'status' => 2);//成功条数
            $successCount = $memberImportModel->count($where);
            $where = array('import_file_id' => $importFile['id'], 'status' => 3);//失败条数
            $errorCount = $memberImportModel->count($where);
        }
        //获得excel基本数据END
        $data = array(
            'lists'        => $consumptionList['lists'],
            'cards'        => $cardInfo,
            'page'         => $page,
            'totalPage'    => $consumptionList['total'] ? ceil($consumptionList['total'] / $pageSize) : 1,
            'successCount' => $successCount,
            'errorCount' => $errorCount,
            'importFile' => $importFile,
            'params'       => array('search_keyword' => $searchKeyword, 'startDate' => $startDate, 'endDate' => $endDate, 'order_status' => $orderStatus, 'fans_level' => $fansLevel)
        );
        $data['loadModuleScript'] = true; //加载方法名对应的js
        $this->display($data, "member/consumpt/default.html");
    }

    public function exportAction()
    {
        $searchKeyword = trim($this->_request->getQuery('search_keyword', ''));
        $startDate = trim($this->_request->getQuery('start_date', ''));
        $endDate = trim($this->_request->getQuery('end_date', ''));
        $orderStatus = intval($this->_request->getQuery('order_status', ''));
        $fansLevel = trim($this->_request->getQuery('fans_level', ''));

        if ($startDate) {
            $startDate = strtotime($startDate);
        }
        if ($endDate) {
            $endDate = strtotime($endDate) + 86399;
        }
        // 查询消费列表
        $shopId = $this->shopId;
        $consumptionList = SellerConsumptionService::consumptionExportList($this->sellerId, $shopId, $searchKeyword, $orderStatus, $fansLevel, $startDate, $endDate);

        $str = "会员,手机号,会员卡级别,下单时间,订单总金额,实付金额,订单状态\n";
        $str = iconv('utf-8', 'gb2312', $str);
        if (!empty($consumptionList['lists'])) {
            foreach ($consumptionList['lists'] as $k => $v) {
                switch ($v['order_status']) {
                    case 1:
                        $orderStatusString = '待付款';
                        break;
                    case 2:
                        $orderStatusString = '待确认';
                        break;
                    case 3:
                        if ($v['order_type'] == 1
                            || $v['order_type'] == 4
                            || $v['order_type'] == 5
                            || $v['order_type'] == 6
                        ) {
                            $orderStatusString = '待核销';
                        } else if ($v['order_type'] == 2) {
                            $orderStatusString = '已发货';
                        }
                        break;
                    case 4:
                        $orderStatusString = '已完成';
                        break;
                    case 5:
                        $orderStatusString = '已关闭';
                        break;
                    case 6:
                        $orderStatusString = '未支付待确认';
                        break;
                    case 7:
                        $orderStatusString = '已确认待上门';
                        break;
                    case 8:
                        $orderStatusString = '已确认待收款';
                        break;
                    case 20:
                        $orderStatusString = '待付订金';
                        break;
                    
                    default:
                        $orderStatusString = '--';
                        break;
                }
                $userName = iconv('utf-8', 'GBK//IGNORE', $v['user_name']); //中文转码
                $phone = iconv('utf-8', 'GBK//IGNORE', $v['phone']);
                $createTime = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) ."\t" :'--';
                $createTime = iconv('utf-8', 'GBK//IGNORE', $createTime);
                $orderAmount = iconv('utf-8', 'GBK//IGNORE', $v['order_amount']);
                $cardName = iconv('utf-8', 'GBK//IGNORE', $v['card_name']);
                $payAmount = iconv('utf-8', 'GBK//IGNORE', $v['pay_amount']);
                $orderStatus = iconv('utf-8', 'GBK//IGNORE', $orderStatusString);
                $str .= $userName . "," . $phone . "," . $cardName . "," . $createTime . "," . $orderAmount . "," . $payAmount . "," . $orderStatus . "\n"; //用引文逗号分开
            }
        }
        $filename = '会员消费纪录' . date('Ymd') . '.csv'; //设置文件名
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . urlencode($filename));
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $str;
    }

    /**
     * 会员消费记录报表导出
     * @author: B.Z.J <baizhijie@dodoca.com>
     * @date: 2017/6/20 9:50
     *
     */
    public function ajaxExportAction()
    {
        if(mc_add('consumptReport_'.$this->shopId.'_'.$this->sellerId.'_'.$this->userId,'add_success',300))
        {
            $searchKeyword = trim($this->_request->getQuery('search_keyword', ''));
            $startDate = trim($this->_request->getQuery('start_date', ''));
            $endDate = trim($this->_request->getQuery('end_date', ''));
            $orderStatus = intval($this->_request->getQuery('order_status', ''));
            $fansLevel = trim($this->_request->getQuery('fans_level', ''));
            $params = array();
            $params['shop_id'] = $this->shopId;
            $params['seller_id'] = $this->sellerId;
            $params['user_id'] = $this->userId;
            $params['file_type'] = 15;
            //文件名
            $params['file_name'] = '会员消费记录';
            //文件路径
            $dataTime = date('Ymdhis', SYS_TIME);
            $params['file_path'] = $this->sellerId . "/" . $this->shopId . "/" . $dataTime . ".csv";
            //文件title
            $header = array('会员', '手机号','会员卡级别','下单时间','订单总金额','实付金额','订单状态');
            $params['file_title'] = serialize($header);
            //查询条件
            $map = array();
            if ($startDate) {
                $startDate = $startDate;
            }
            if ($endDate) {
                $endDate = $endDate + 86399;
            }
            $map['seller_id'] = $this->sellerId;
            $map['shop_id'] = $this->shopId;
            $map['search_keyword'] = $searchKeyword;
            $map['order_status'] = $orderStatus;
            $map['fans_level'] = $fansLevel;
            $map['start_date'] = $startDate;
            $map['end_date'] = $endDate;
            $map['page'] = 1;
            $map['pageSize'] = 10;
            $params['select_conditions'] = json_encode($map);
            // 查询消费列表
            $consumptionList = SellerConsumptionService::consumptionExportList($this->sellerId, $this->shopId, $searchKeyword, $orderStatus, $fansLevel, $startDate, $endDate);
            if(empty($consumptionList))
            {
                $this->ajaxReturn(array('code' => -1, 'msg' => '暂无数据'));
            }
            //添加数据
            $result = Order_ReportService::addReport($params);
            //返回结果
            if($result === FALSE)
            {
                $this->ajaxReturn(array('code' => -1, 'msg' => '报表生成失败'));
            }

            $this->ajaxReturn(array('code' => 1, 'msg' => '报表生成中'));
        }
        else
        {
            $this->ajaxReturn(array('code' => -1, 'msg' => '请五分钟后重新生成'));
        }
    }
}